package person.locke.regexandgame.regex;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Locke on 2018/7/4.
 */
public class WordCountAndLocate {

    public Map<String,WordFrequency> countAndLocate(String[] targets, String text){

        Map<String,WordFrequency> map = new HashMap<String, WordFrequency>();

        for(String target:targets){

            WordFrequency wf = countAndLocate(target,text);

            map.put(target,wf);

        }

        return map;
    }

    public WordFrequency countAndLocate(String target,String text){

        StringBuilder stringBuilder = new StringBuilder("(?i)"+target);

        Pattern pattern = Pattern.compile(stringBuilder.toString());

        Matcher m = pattern.matcher(text);

        List<Location> locations = new ArrayList<Location>();

        while(m.find()){

            Location location = new Location(m.start(),m.end(),text.substring(m.start(),m.end()));

            locations.add(location);

        }


        return new WordFrequency(locations);
    }


}
